var ObjectId = require('mongodb').ObjectID;

var CommonBase = require('./commonBase');


var ModelBase = function(){}
ModelBase.__proto__ = CommonBase;
ModelBase.baseModel = null;
ModelBase.modelName = '';

module.exports = ModelBase;

ModelBase.getByOID = function(oid, callback){
    if(this.CheckParam(callback, oid)){
        oid = new ObjectId(oid);
        this.baseModel.findOne({'_id' : oid}, this.ReturnFunction(callback, 'Error in getting a ' + this.modelName + ' by oid'));
    }
};

ModelBase.getByWhere = function(where, callback){
    if(this.CheckParam(callback, where)){
        this.baseModel.find(where, this.ReturnFunction(callback, 'Error in getting ' + this.modelName + ' by where'));
    }
}

ModelBase.getAll = function(callback){
    this.baseModel.find({}, this.ReturnFunction(callback, 'Error in getting all ' + this.modelName + ' items '));
}

ModelBase.update = function(item, callback){
    if(this.CheckParam(callback, item)){
        var where = {'_id' : item._id};
        delete item['_id'];
        this.baseModel.update(where, item, this.ReturnFunction(callback, 'Error in updating'))
    }
}

ModelBase.save = function(item, callback){
    if(this.CheckParam(callback, item)){
        item = new this.baseModel(item);
        item.save(function(err, result){
            if(err){
                console.log('Error in saving new ' + this.modelName);
                return callback(err);
            }
            result = JSON.parse(JSON.stringify(result));
            return callback(null, result);
        });
    }
}

ModelBase.delete = function(oid, callback){
    if(this.CheckParam(callback, oid)){
        oid = new ObjectId(oid);
        this.baseModel.remove({'_id' : oid}, this.ReturnFunction(callback, 'Error in removing a ' + this.modelName + ' by oid'));
    }
}